package com.gxa.javaserver.socket;

import com.gxa.javaserver.service.impl.ProcessDataService;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;

/**
 * 服务端的线程
 * @author:Teacher黄
 * @date:Created at 2020/06/16
 */
public class ServerThread2 extends Thread {


    /**
     * socket连接对象
     */
    private Socket socket;

    /**
     * 输入流
     */
    private InputStreamReader inputStreamReader;

    /**
     * 处理数据的对象
     */
    private ProcessDataService processDataService;


    /**
     * 构造器
     * @param socket
     */
    public ServerThread2(Socket socket) {
        this.socket = socket;
    }


    /**
     * 包含处理数据对象的构造器
     * @param socket
     * @param processDataService
     */
    public ServerThread2(Socket socket, ProcessDataService processDataService) {
        this.socket = socket;
        this.processDataService = processDataService;
    }

    @Override
    public void run() {
        try {
            // 获取客户端信息
            InetAddress inetAddress = socket.getInetAddress();
            // ip
            String ipAddress = inetAddress.getHostAddress();
            System.out.println("客户端:"+ipAddress+",连接成功!");
            // 准备输入输出流
            inputStreamReader = new InputStreamReader(socket.getInputStream(),"UTF-8");
            // 接收客户端的消息
            String data = getData(inputStreamReader);
            System.out.println("客户端:"+data);
            // 处理数据
            processDataService.process(data);


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            closeResources(inputStreamReader, socket);
        }

    }


    /**
     * 获取数据的重载
     * @param inputStreamReader
     * @return
     * @throws IOException
     */
    private String getData(InputStreamReader inputStreamReader) throws IOException {
        // 准备一个char数组用来接收读取的数据
        char[] chars = new char[1024];
        // 读取的量
        int read;

        // 这个地方需要拼接字符串, 不能使用+, 用StringBuilder
        StringBuilder stringBuilder = new StringBuilder();
        while ((read = inputStreamReader.read(chars)) != -1){
            System.out.println("读取了:"+read+"个字符!");
            stringBuilder.append(new String(chars, 0, read));
        }
        // 转换成字符串 并返回
        return stringBuilder.toString();
    }


    /**
     * 关闭资源的方法
     * @param inputStreamReader
     * @param socket
     */
    private void closeResources(InputStreamReader inputStreamReader, Socket socket){
        try {
            if(inputStreamReader != null){
                inputStreamReader.close();
            }

            if (socket != null) {
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
